import $V from './$V';
export default function mydd(high, low, close, length) {
    let ret1 = $V.init(high.length, 0);
    let ret2 = $V.init(high.length, 0);
    for (let i = length - 1; i < high.length; i++) {
        const max = $V.vmax($V.subv(close, i - length + 1, i + 1));
        const min = $V.vmin($V.subv(close, i - length + 1, i + 1));
        let upToMax = 1, upToMaxValue  = 0;
        let downToGold = 1, downToGoldValue = 0;
        let downToLow = 1, downToLowValue = 0;
        let upToGold = 1, upToGoldValue = 0;
        const delta = max[1] - min[1];
        const goldMax = max[1] - delta * 0.618;
        const goldMin = min[1] + delta * 0.382;
        for(let k = i - length + 1 + max[0]; k >= i - length + 1; k--) {
            // 向后寻找小于0.618的值
            if(close[k] < goldMax) {
                upToMaxValue = (max[1] - close[k]);
                break;
            }
            upToMax++;
        }
        if(upToMax === max[0]) {
            upToMaxValue = max[1] - close[i - length + 1];
        }
        for(let k = i - length + 1 + max[0]; k <= i; k++) {
            if (close[k] < goldMax) {

                downToGoldValue = close[k] - max[1];
                break;
            }
            downToGold++;
        }
        if (downToGold === i - max[0]) {
            downToGoldValue = close[i] - max[1];
        }
        for(let k = i - length + 1 + min[0]; k >= i - length + 1; k--) {
            if (close[k] > goldMin) {
                downToLowValue = min[1] - close[k];
                break;
            }
            downToLow++
        }
        if (downToLow === min[0]) {
            downToLowValue = min[1] - close[i - length + 1];
        }
        for(let k = i - length + 1 + min[0]; k <= i; k++) {
            if (close[k] > goldMin) {
                upToGoldValue =  close[k] - min[1];
                break;
            }
            upToGold++
        }
        if (upToGold === i - min[0]) {
            downToLowValue = close[i] - min[1];
        }
        let rate = (upToMaxValue / upToMax + upToGoldValue / upToGold + (downToGoldValue / downToGold + downToLowValue / downToLow)) / delta/ length;
        ret1[i] = rate;
        ret2[i] = -(downToGoldValue / downToGold + downToLowValue / downToLow) / delta * length;
    }
    return {myd: ret1, myd2: ret2};
}
